// JavaScript Document

// Check xem trình duyệt là IE6 hay IE7
var isIE		= (navigator.userAgent.toLowerCase().indexOf("msie") == -1 ? false : true);
var isIE6	= (navigator.userAgent.toLowerCase().indexOf("msie 6") == -1 ? false : true);
var isIE7	= (navigator.userAgent.toLowerCase().indexOf("msie 7") == -1 ? false : true);
var isChrome= (navigator.userAgent.toLowerCase().indexOf("chrome") == -1 ? false : true);

function addCommas(nStr){
	nStr += ''; x = nStr.split(',');	x1 = x[0]; x2 = ""; x2 = x.length > 1 ? ',' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + '.' + '$2'); } return x1 + x2;
}

function checkAjaxResponse(response){
	if(response.substr(0, 7) == "[error]"){
		alert(response.replace("[error]", "").replace(/<br \/>/gi, '\n').replace(/\&bull;/gi, '-'));
		return false;
	}
	return true;
}

function checkForm(form_name, arrControl){
	
	frm	= eval("document." + form_name + ";");
	
	for(i=0; i<arrControl.length; i++){
		
		arrTemp	= arrControl[i].split("{#}");
		type		= arrTemp[0];
		defVal	= arrTemp[1];
		control	= arrTemp[2];
		title		= arrTemp[3];
		ob			= eval("frm." + control + ";");
		errMsg	= "";
		switch(type){
			case "0": if($.trim(ob.value) == "" || $.trim(ob.value) == defVal){ errMsg = "Bạn chưa nhập " + title + "."; } break;
			case "1": if(parseFloat(ob.value) <= parseFloat(defVal)){ errMsg = title + " phải lớn hơn " + addCommas(defVal) + "."; } break;
			case "2": if(ob.value == defVal){ errMsg = "Bạn chưa chọn " + title + "."; } break;
			case "3": if(!isEmail(ob.value)){ errMsg = title + " không hợp lệ."; } break;
			case "4": if($.trim(ob.value).length < defVal){ errMsg = title + " phải có ít nhất " + addCommas(defVal) + " ký tự."; } break;
			case "5": if(!isUrl(ob.value)){ errMsg = title + " không hợp lệ."; } break;
			case "6": if(parseFloat(ob.value) < parseFloat(defVal)){ errMsg = title + " phải lớn hơn hoặc bằng " + addCommas(defVal) + "."; } break;
			case "7": if(parseFloat(ob.value) > parseFloat(defVal)){ errMsg = title + " phải nhỏ hơn hoặc bằng " + addCommas(defVal) + "."; } break;
		}
		
		if(errMsg != ""){
			
			alert(errMsg);
			
			// Check xem có moveScrollTop hay không
			defTop = 40;
			if(typeof($("form[name='" + form_name + "']").attr("fixScrollTop")) != "undefined"){
				defTop	= $("form[name='" + form_name + "']").attr("fixScrollTop");
			}
			move		= 0;
			obTemp	= $("form[name='" + form_name + "'] [name='" + control + "']");
			if($(window).scrollTop() + defTop < obTemp.offset().top){
				if((obTemp.offset().top - ($(window).scrollTop() + $(window).height())) > 0) move = 1;
			}
			else move = 1;
			
			// Move or focus
			if(move == 0) ob.focus();
			else moveScrollTop(obTemp, { top: defTop, finish: function(){ obTemp.focus(); } });
			
			return false;
			
		}// End if(errMsg != "")
		
	}// End for(i=0; i<arrControl.length; i++)
	
	// Nếu có thêm javascript thì execute
	args	= checkForm.arguments;
	if(typeof(args[2]) != "undefined"){
		opts	= { stop: false, callback: null }
		switch(typeof(args[2])){
			case "string"	: eval(args[2]); break;
			case "function": args[2](); break;
			case "object"	: $.extend(opts, args[2]); break;
		}
		if(typeof(opts.callback) == "function") opts.callback();
		if(opts.stop == true) return false;
	}
	
	if(typeof(formErrorOnSubmit) != "undefined" && formErrorOnSubmit[form_name] == 1) return false;
	// Nếu là form post_final thì khi không có lỗi phải disabled mấy nút submit đi để user không click nhiều, tránh duplicate
	if(form_name == "post_final"){
		$("form[name='" + form_name + "'] :submit").attr("disabled", "disabled").val("Vui lòng đợi...").blur();
	}
	
	// Submit form
	frm.submit();
	
}

function fixImageSize(width, height, maxWidth, maxHeight){
	// Check if the current width is larger than the max
	ratio		= maxWidth / width;   // Get ratio for scaling image
	w			= maxWidth;
	h			= height * ratio;    // Reset height to match scaled image
	// Check if current height is larger than max
	if(h > maxHeight){
		ratio	= maxHeight / height; // Get ratio for scaling image
		w		= width * ratio;    // Reset width to match scaled image
		h		= maxHeight;
	}
	return Array(parseInt(w), parseInt(h));
}

function formatCurrency(div_id, str_number){
	document.getElementById(div_id).innerHTML = addCommas(str_number);
}

function isEmail(s){
	var re	= /^(\w|[^_]\.[^_]|[\-])+(([^_])(\@){1}([^_]))(([a-z]|[\d]|[_]|[\-])+|([^_]\.[^_]) *)+\.[a-z]{2,3}$/i;
	return re.test(s);
}

function isUrl(s){
	var re	= /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	return re.test(s);
}

function moveScrollTop(ob){
	args	= moveScrollTop.arguments;
	opts	= {
		top	: 40,
		time	: 1000,
		finish: false
	};
	if(typeof(args[1] != "undefined")) $.extend(opts, args[1]);
	if(!isChrome) $("html").animate({ scrollTop: (ob.offset().top - opts.top) }, opts.time, "easeOutExpo", opts.finish);
	else $("body").animate({ scrollTop: (ob.offset().top - opts.top) }, opts.time, "easeOutExpo", opts.finish);
}

function showSkype(nick, text, max_length){
	name	= (text.length <= max_length || max_length == 0) ? text : text.substr(0, max_length) + "...";
	document.write('<a title="' + text + '" class="text_link" href="skype:' + nick + '?chat" rel="nofollow">' + name + '</a>');
}

function showYM(nick, icontype, text, max_length){
	name	= (text.length <= max_length || max_length == 0) ? text : text.substr(0, max_length) + "...";
	document.write('<a title="' + text + '" class="text_link" href="ymsgr:sendim?' + nick + '&m=Xin chao, toi muon hoi ve san pham ' + window.location.href + ' !" rel="nofollow" style="background-image:url(http://opi.yahoo.com/online?u=' + nick + '&m=g&t=' + icontype + '&l=us)">' + name + '</a>');
}

function tooltipProduct(ob){
	if(isIE6 || isIE7) return;
	// Nếu có khai báo ob thì gán luôn cho strTooltipProductOb
	if(typeof(ob) != "undefined") strTooltipProductOb = ob;
	// Nếu ko tồn tại strTooltipProductOb thì return luôn
	if(typeof(strTooltipProductOb) == "undefined") return;
	// Bẻ ra array
	arrTooltipProductOb	= strTooltipProductOb.split(",");
	// Lấy array unique
	arrTooltipProductOb	= $.unique(arrTooltipProductOb);
	// Lấy obj để đưa vào jquery
	obj	= "";
	$.each(arrTooltipProductOb, function(index, value){
		if(obj != "") obj += ",";
		obj += $.trim(value);
	});
	$(obj).each(function(index, domEle){
		var obTT	= $(domEle).parent().find(".tooltip");
		var img	= $(domEle).parent().find(".tooltip img");
		obTT.tooltip({
			bodyHandler: function(){
				tooltipWidth	= (typeof(obTT.attr("tooltipWidth")) != "undefined" ? obTT.attr("tooltipWidth") : 350);
				$("#tooltip").css("width", tooltipWidth + "px");
				$(domEle).find(".picture, .picture_only").html(function(index, html){
					width			= (typeof($(this).attr("width"))	!= "undefined" ? $(this).attr("width") : img.width());
					height		= (typeof($(this).attr("height"))!= "undefined" ? $(this).attr("height") : img.height());
					maxWidth		= (typeof($(this).attr("maxWidth"))	!= "undefined" ? $(this).attr("maxWidth") : 350);
					maxHeight	= (typeof($(this).attr("maxHeight"))!= "undefined" ? $(this).attr("maxHeight") : 350);
					arrFixSize	= fixImageSize(width, height, maxWidth, maxHeight);
					return '<img width="' + arrFixSize[0] + '" height="' + arrFixSize[1] + '" src="' + $(this).attr("src") + '" />';
				});
				return $(domEle).html();
			},
			track: true,
			showURL: false,
			extraClass: "tooltip_product"
		});
	});
}

function footerLoad(){
	
}

function initLoad(){
	tooltipProduct();
}

function initLoaded(){
	
}